<template>
	<view class="tempalte">
		<cl-nav-bar></cl-nav-bar>
		<view class="tempalte_title">
			<text class="tempalte_title_text">模板标题</text>
			<uni-easyinput v-model="templateData.name" placeholder="模板标题无法修改,请慎重填写" :disabled="type === 'edit'" />
		</view>

		<view class="tempalte_fields">
			<text class="tempalte_fields_text">字段设置</text>
			<l-drag :list="templateData.fieldList" @change="getNewList" ref="dragRef" :column="1" :touchHandle="touchHandle"
				gridHeight="90rpx" handle>
				<template #grid="{ active, content, oindex, index }">
					<view class="tempalte_fields_item" :class="{ tempalte_fields_item_active: active }"
						@click.stop="handleEditField(content)">
						<view class="flex_end_center">
							<image class="w_50 h_50 mr_20" src="../../static/del_icon.png"
								@click.stop="handleDel($event, index, oindex)" />
							<text> {{ content.label }} </text>
						</view>

						<view class="flex_end_center">
							<text class="tempalte_fields_item_type">{{
                content.typeName
              }}</text>
							<uni-icons style="margin-left: 4rpx" type="right" size="16"></uni-icons>
							<uni-icons style="margin-left: 4rpx" type="bars" size="16" @touchstart="touchHandle = true"
								@touchend="touchHandle = false"></uni-icons>
						</view>
					</view>
				</template>
			</l-drag>
			<view class="tempalte_add" @click="handleAddField">
				<image class="tempalte_add_img" src="../../static/add_icon.png" />
				<text class="tempalte_add_text">新增字段</text>
			</view>
		</view>
		<view class="g_bottom_box">
			<view class="g_bottom_box_btn" @click="handleSubmit">保存</view>
		</view>
	</view>
	<FieldEdit ref="fieldEditRef" @saveField="handleSaveField"></FieldEdit>
</template>

<script setup>
	import {
		cloneDeep
	} from 'lodash'
	import FieldEdit from './field-edit.vue'
	import {
		getUuid
	} from '@/utils/uuid.js'
	import {
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		createTemplateJson,
		getDirList,
		getJsonData,
		removeDir,
		moveFile,
		getOrCreateDir,
	} from '../../utils/file'
	import {
		formatDate
	} from '../../utils'
	let eventChannel = null
	let type = ref('add')
	// 获取id
	const templateData = ref({
		name: '模板标题',
		fieldList: [],
		templateId: getUuid(),
	})
	const touchHandle = ref(false)
	const dragRef = ref()
	// 原始文件名
	let originDirName = ref('')
	let disabled = ref(false)
	onLoad(() => {
		uni.showLoading({
			title: '字段加载中',
			mask: true,
		})
		const instance = getCurrentInstance().proxy
		eventChannel = instance.getOpenerEventChannel()
		eventChannel.on('acceptDataFromOpenerPage', async function(data) {
			if (data) {
				originDirName.value = data
				const res = await getJsonData(
					`_doc/templateList/${data}/templateData.json`
				)
				// 检查是否有填报数据
				// const fillList = await getDirList(`_doc/templateList/${data}/fillList`)
				// if (fillList.length > 0) {
				//   disabled.value = true
				// }
				templateData.value = JSON.parse(res.result)
				type.value = 'edit'
			}
			uni.hideLoading()
		})
	})

	const getNewList = (newList) => {
		let resList = newList.map((item) => item.content)
		templateData.value.fieldList = resList
	}

	const fieldEditRef = ref()
	// 新增
	const handleAddField = () => {
		fieldEditRef.value.open()
	}
	// 删除
	const handleDel = (e, idx) => {
		uni.showModal({
			title: '提示',
			content: '确认删除该字段？',
			showCancel: true,
			success: ({
				confirm,
				cancel
			}) => {
				if (confirm) {
					templateData.value.fieldList.splice(idx, 1)
				}
			},
		})
	}
	// 编辑
	const handleEditField = (item) => {
		fieldEditRef.value.open()
		fieldEditRef.value.setData(cloneDeep(item))
	}
	// 字段保存
	const handleSaveField = (fieldData) => {
		if (fieldData.field_id) {
			let editIdx = templateData.value.fieldList.findIndex(
				(item) => item.field_id === fieldData.field_id
			)
			if (editIdx > -1) {
				templateData.value.fieldList.splice(editIdx, 1, fieldData)
			}
		} else {
			fieldData.field_id = getUuid()
			dragRef.value.push(fieldData)
		}
	}

	// 提交事件
	const handleSubmit = async () => {
		if (templateData.value.fieldList.length === 0) {
			return uni.showToast({
				title: '字段不能为空！',
				icon: 'error',
				duration: 1000,
				mask: true,
			})
		}
		// const flag = dirList.some((dirName) => {
		//   const index = dirName.indexOf('_')
		//   if (index > -1) {
		//     return dirName.slice(index + 1) === templateData.name
		//   }
		// })
		// if (flag) {
		//   return uni.showToast({
		//     title: '模板名称不能重复',
		//     icon: 'error',
		//     duration: 1000,
		//     mask: true,
		//   })
		// }
		uni.showLoading({
			title: '数据保存中'
		})
		if (type.value === 'edit') {
			templateData.value.editTime = formatDate()
			// if (originDirName.value !== (`${templateData.value.templateId}_${templateData.value.name}`)) {
			// 	await moveFile(
			// 		`_doc/templateList/${originDirName.value}`,
			// 		`_doc/templateList/`,
			// 		`${templateData.value.templateId}_${templateData.value.name}`)
			// }
		} else {
			templateData.value.createTime = formatDate()
		}
		createTemplateJson(templateData.value)
			.then((res) => {
				uni.showToast({
					title: '保存成功！',
					icon: 'success',
					success: () => {
						setTimeout(() => {
							uni.navigateBack({
								success: () => {
									eventChannel.emit('acceptDataFromOpenedPage', {
										type: type.value,
										templateData: templateData.value,
									})
								},
							})
						}, 1000)
					},
				})
			})
			.catch(() => {
				uni.showToast({
					title: '保存失败！',
					icon: 'error'
				})
			})
	}
</script>

<style scoped lang="scss">
	.tempalte {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		overflow: hidden;

		&_title {
			padding: 20rpx 10rpx;
			display: flex;
			align-items: center;
			background-color: #fff;

			&_text {
				margin-right: 20rpx;
			}
		}

		&_fields {
			margin-top: 20rpx;
			flex: 1;
			overflow: auto;

			&_text {
				padding-left: 20rpx;
				color: $uni-text-color-placeholder;
				font-size: 20rpx;
			}

			&_item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
				border-bottom: 1px solid gainsboro;
				background-color: #fff;

				&_active {
					background-color: ghostwhite;
				}

				&_type {
					margin-left: 40rpx;
					font-size: 24rpx;
					color: #5c5c5c;
				}
			}
		}

		&_add {
			padding: 20rpx;
			background-color: #fff;
			display: flex;
			align-items: center;

			&_img {
				width: 50rpx;
				height: 50rpx;
			}

			&_text {
				margin-left: 10rpx;
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.field {
		padding: 10rpx;
		box-sizing: border-box;

		&_body {
			margin-top: 20rpx;
			flex: 1;
		}

		.options_box {
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			&_add,
			&_del {
				margin-left: 10rpx;
				width: 40rpx;
				height: 40rpx;
				cursor: pointer;
			}
		}
	}
</style>